'use strict';

const Controller = require('egg').Controller;

class BannerController extends Controller {
  // 根据id查询
  async getBannerById() {
    this.ctx.validate({
      _id: 'string'
    }, this.ctx.params);

    let channel = await this.ctx.app.model.Banner.get(this.ctx.params._id)
    this.ctx.body = {
      code: 0,
      data: channel
    }
  }

  // 新建
  async createBanner() {
    let banner = new this.ctx.app.model.Banner(this.ctx.request.body)
    let doc = await banner.save()

    this.ctx.body = {
      code: 0,
      msg: '创建成功'
    }
  }

  // 获取列表
  async getBannerList() {
    let name = this.ctx.request.query.name;
    let query1 = name ? { name: new RegExp(name) } : {}

    let bannerType = this.ctx.request.query.bannerType;
    let query2 = bannerType ? { bannerType } : {}

    let query = Object.assign(query1, query2)

    let sort = {}
    let pageSize = parseInt(this.ctx.request.query.pageSize)
    let page = parseInt(this.ctx.request.query.page) || 0
    let skip = pageSize * (page - 1)

    let count = await this.ctx.app.model.Banner.count()
    let banners = await this.ctx.app.model.Banner.list(query, sort, pageSize, skip)

    this.ctx.body = {
      code: 0,
      data: {
        list: banners,
        count: count,
        nextPage: page + 1
      }
    }
  }

  async updateBannerById() {
    this.ctx.validate({
      _id: 'string'
    }, this.ctx.params);

    let _id = this.ctx.params._id
    let body = this.ctx.request.body

    let r = await this.ctx.app.model.Banner.update({ _id: _id }, body)

    this.ctx.body = {
      code: 0,
      msg: '更新成功'
    }
  }

  async deleteBannerById() {
    this.ctx.validate({
      _id: 'string'
    }, this.ctx.params);

    let _id = this.ctx.params._id
    let r = await this.ctx.app.model.Banner.remove({ _id: _id })

    this.ctx.body = {
      code: 0,
      msg: '删除成功'
    }
  }

  // 获取列表
  async getAllBannerList() {
    let count = await this.ctx.app.model.Banner.count()
    let banners = await this.ctx.app.model.Banner.list({}, {}, 9999, 0)

    this.ctx.body = {
      code: 0,
      data: {
        list: banners,
        count: count
      }
    }
  }
}

module.exports = BannerController;
